//
//  WenBaDetailHeader.m
//  suRead
//
//  Created by nancy  on 16/9/18.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "WenBaDetailHeader.h"

#import "M_WenbaDetail.h"
#import "FMDBHelpers.h"
#import "ServiceNews.h"

#import "UIImageView+WebCache.h"
#import "UIControl+Blocks.h"
#import <Masonry/Masonry.h>

#define ScreenRectWidth [UIScreen mainScreen].applicationFrame.size.width

@interface WenBaDetailHeader()
@property (weak, nonatomic) IBOutlet UIImageView *imageViewIcon;
@property (weak, nonatomic) IBOutlet UILabel *labelTitle;
@property (weak, nonatomic) IBOutlet UILabel *labelCreateTime;

@property (weak, nonatomic) IBOutlet UILabel *labelViewCount;
@property (weak, nonatomic) IBOutlet UIButton *showmoretextBtn;
@property (weak, nonatomic) IBOutlet UIImageView *expandIcon;
@property (weak, nonatomic) IBOutlet UILabel *labelQuestionCount;
@property (weak, nonatomic) IBOutlet UILabel *labelStatus;
@property (weak, nonatomic) IBOutlet UIImageView *viewIcon;
@property (weak, nonatomic) IBOutlet UIImageView *zhuanjiaIcon;
@property (weak, nonatomic) IBOutlet UILabel *zhuanjia_nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *zhuanjia_descriptionLabel;
@property (weak, nonatomic) IBOutlet UIView *categoryView;
@property (nonatomic,strong) M_WenbaDetail *wenbaDetail;

@end

@implementation WenBaDetailHeader

- (void)awakeFromNib {
    // Initialization code
    if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
        self.layoutMargins = UIEdgeInsetsZero;
        self.preservesSuperviewLayoutMargins = NO;
        self.separatorInset = UIEdgeInsetsMake(0, 10.0f, 0, 10.0f);
    }
}

+ (CGFloat)heightWithContent:(M_WenbaDetail *)wenbaDetailData_
{
    
    //底部高度
    CGFloat height_ = 80.0f;
    
    //图片高度
    CGFloat imgHeight =ScreenRectWidth/2;
    height_ += imgHeight;
    
    
    //标题高度
    NSString *title =wenbaDetailData_.f_zhuanjia_description;

    CGFloat contentHeight=0.0f;
    NSRange range = [title rangeOfString:@"</span>"];//判断字符串是否包含
    if (range.location !=NSNotFound)
    {
        NSString *jsString = [NSString stringWithFormat:@"<style type=\"text/css\"> \n"
                              "span,pre{color: #9e9e9f;font-size: .8rem;}"
                              "</style> \n"
                              "%@ \n",title];
        NSAttributedString * attrStr       = [[NSAttributedString alloc] initWithData:[jsString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        
        contentHeight  = [attrStr boundingRectWithSize:CGSizeMake(ScreenRectWidth - 20.0f, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size.height;
        
    }
    else {
        contentHeight = [title boundingRectWithSize:CGSizeMake(ScreenRectWidth - 20.0f, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f]} context:nil].size.height;
    }
    //contentHeight为实际内容高度，如果高度大于60.0f并且是收起状态，则高度=60.0f
    if(contentHeight>60.0f){
        if(!wenbaDetailData_.isShowMoreText){
            //收起的高度
            contentHeight=60.0f;
            
        }
    }
    
    height_ += contentHeight;
    return height_;
}

- (void)setWenbaDetailData:(id)wenbaDetailData
{
    _wenbaDetail = (M_WenbaDetail *)wenbaDetailData;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    
    [self.imageViewIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.contentView);
        make.height.equalTo(@(screenSize.width/2));
    }];
    
    NSString *imageURL = _wenbaDetail.f_background_img;
    [self.imageViewIcon sd_setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"lazy"]];
    
    self.labelTitle.text = _wenbaDetail.f_zhuanjia_description;
    
    
    NSString *createTime = _wenbaDetail.f_updateTime;
    self.labelCreateTime.text = createTime;
    
    self.labelViewCount.text = [NSString stringWithFormat:@"%ld",_wenbaDetail.f_views];
    
    [self.labelStatus setText:_wenbaDetail.f_zhuanjia_status];
    
    NSString *labelQuestionCountText=[NSString stringWithFormat:@"共%@个提问，%@个回复",_wenbaDetail.f_zhuanjia_proNum,_wenbaDetail.f_zhuanjia_replyNum];

    self.labelQuestionCount.text=labelQuestionCountText;

    self.zhuanjiaIcon.layer.cornerRadius  = 20.0;//设置图片圆角的尺度
    self.zhuanjiaIcon.layer.masksToBounds = YES;//没这句话它圆不起来
    //    self.userPhoto.image = [UIImage imageNamed:@"icon_user"];
    [self.zhuanjiaIcon sd_setImageWithURL:[NSURL URLWithString:_wenbaDetail.f_zhuanjia_img] placeholderImage:[UIImage imageNamed:@"icon_user"]];
    self.zhuanjia_nameLabel.text=_wenbaDetail.f_zhuanjia_name;
    self.zhuanjia_descriptionLabel.text=_wenbaDetail.f_zhuanjia_touxian;
    
    NSString *title =self.labelTitle.text;
    CGFloat contentHeight=[self heightWithTitle:title];
    
    if(contentHeight<=60.0f){
        [_showmoretextBtn setHidden:YES];
        [_expandIcon setHidden:YES];
    }else{
        [_showmoretextBtn setHidden:NO];
        [_expandIcon setHidden:NO];
    }

    [_showmoretextBtn addTarget:self action:@selector(showMoreText) forControlEvents:UIControlEventTouchUpInside];
    
    NSArray  *categorylist=_wenbaDetail.f_category;
    
    CGFloat tagDistance = 10.0f;
    CGFloat tagPadding  = 5.0f;
    CGFloat tagHeight   = 18.0f;
    UIFont  *tagFont    = [UIFont systemFontOfSize:12.0f];
    
    
    
    __block CGFloat currentX =screenSize.width-20;
    __block CGFloat currentY = 3;
    
    
    for (NSDictionary *itemDic in categorylist){
        
        NSString *categoryName = [itemDic objectForKey:@"name"];
        
        NSString *categoryurl=[itemDic objectForKey:@"url"];
        
        CGSize size = [categoryName sizeWithAttributes:@{NSFontAttributeName: tagFont}];
        
        UIButton *ctgButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [ctgButton addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
            //去问吧专题列表
            if ([_wenBaDetailHeaderDelegate respondsToSelector:@selector(toWenBaCtgListPage:)]) { // 如果协议响应了sendValue:方法
                [_wenBaDetailHeaderDelegate toWenBaCtgListPage:categoryurl]; // 通知执行协议方法
            }
            
        }];
        [ctgButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [ctgButton setTitle:categoryName forState:UIControlStateNormal];
        ctgButton.layer.borderWidth = 0.5f;
        ctgButton.layer.borderColor = [UIColor whiteColor].CGColor;
        ctgButton.layer.cornerRadius=5.0f;
        ctgButton.layer.masksToBounds = YES;
        ctgButton.titleLabel.font = tagFont;
        [self.categoryView addSubview:ctgButton];
        
        [ctgButton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            //先判断当前行是否放的下
            currentX = (currentX -tagPadding * 2 -size.width-tagDistance);
            make.left.equalTo(ctgButton.superview).offset(currentX);
            make.top.equalTo(ctgButton.superview).offset(currentY);
            make.size.mas_equalTo(CGSizeMake(tagPadding * 2 + size.width, tagHeight));
            
        }];
        
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    if(self.wenbaDetail.isShowMoreText){
        [_expandIcon setImage:[UIImage imageNamed:@"icon_collapse"]];
    }else{
        [_expandIcon setImage:[UIImage imageNamed:@"icon_expand"]];
    }
    
}

- (void)showMoreText
{
    //将当前对象的isShowMoreText属性设为相反值
    self.wenbaDetail.isShowMoreText = !self.wenbaDetail.isShowMoreText;
    if (self.showMoreTextBlock)
    {
        self.showMoreTextBlock(self);
    }
}

-(CGFloat)heightWithTitle:content_
{
    CGFloat contentHeight=0.0f;
    NSRange range = [content_ rangeOfString:@"</span>"];//判断字符串是否包含
    if (range.location !=NSNotFound)
    {
        NSString *jsString = [NSString stringWithFormat:@"<style type=\"text/css\"> \n"
                              "span,pre{color: #9e9e9f;font-size: .8rem;}"
                              "</style> \n"
                              "%@ \n",content_];
        NSAttributedString * attrStr       = [[NSAttributedString alloc] initWithData:[jsString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        
        contentHeight  = [attrStr boundingRectWithSize:CGSizeMake(ScreenRectWidth - 20.0f, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size.height;
        
    }
    else {
        contentHeight = [content_ boundingRectWithSize:CGSizeMake(ScreenRectWidth - 20.0f, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f]} context:nil].size.height;
    }
    return contentHeight;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

@end